/**
 * 标签栏目
 */
import * as types from "../type";
const state = {
  // 存放所有浏览过的且不重复的路由数据
  visitedTag: JSON.parse(sessionStorage.getItem("visitedTag")) || [],
  //存放左侧被激活的菜单
  activeMenuName: sessionStorage.getItem("activeMenuname") || ""
};

const getters = {
  visitedTag: state => state.visitedTag,
  activeMenuName: state => state.activeMenuName
};

const mutations = {
  [types.ADD_TAG](state, response) {
    // 打开新页签--添加路由数据的方法
    if (
      state.visitedTag.some(item => item.path === response.path) ||
      response.name === "index"
    ) {
      return;
    }
    state.visitedTag.push({
      name: response.name,
      path: response.path,
      title: response.meta.title || "no-title"
    });
    sessionStorage.setItem("visitedTag", JSON.stringify(state.visitedTag));
  },
  [types.DEL_TAG](state, path) {
    state.visitedTag.splice(
      state.visitedTag.findIndex(item => item.path === path),
      1
    );
    sessionStorage.setItem("visitedTag", JSON.stringify(state.visitedTag));
  },
  [types.SET_ACTIVE_MENU_NAME](state, name) {
    state.activeMenuName = name;
    sessionStorage.setItem("activeMenuName", name);
  }
};

const actions = {
  addTag: ({ commit }, data) => {
    commit(types.ADD_TAG, data);
  },
  delTag: ({ commit }, path) => {
    return new Promise(resolve => {
      // resolve方法：未来成功后回掉的方法
      commit(types.DEL_TAG, path);
      resolve(state.visitedTag);
    });
  },
  setActiveMenuName: ({ commit }, name) => {
    commit(types.SET_ACTIVE_MENU_NAME, name);
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
